/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.pima.gestrest.converter;

import com.pima.gestrest.controller.CuisineController;
import com.pima.gestrest.model.Cuisine;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.SelectItem;

/**
 *
 * @author Pierre-Louis Conte
 */
@FacesConverter("cuisineConverter")
public class CuisineConverter implements Converter {

    @Override
    public Cuisine getAsObject(FacesContext fc, UIComponent uic, String string) {
       //  throw new UnsupportedOperationException("Not supported yet.");

        String [] str_tab;
        str_tab = string.split(", ");

        CuisineController cuisineController = (CuisineController)fc.getApplication().getELResolver().getValue(fc.getELContext(), null, "cuisineController");
        for(SelectItem item : cuisineController.getItemList())
        {
            Cuisine cuisine = (Cuisine)item.getValue();
            if(cuisine.getId().toString().equals(str_tab[0]) && cuisine.getTitle().equals(str_tab[1]) && cuisine.getRegion().equals(str_tab[2]))
            {
                return cuisine;
            }
        }

        return null;
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object o) {
      //  throw new UnsupportedOperationException("Not supported yet.");
      return ((Cuisine)o).getId()+", "+((Cuisine)o).getTitle() + ", " + ((Cuisine)o).getRegion();
    }

}
